from iFinDPy import *
from DataProcess.Ifindfunctions import IFind_DailyQuote
import chardet
import datetime
import pandas as pd

# ---更新股票列表---
def Download_Stock_List(database, cold_start=False):
    # 数据池-免费用户专用_板块成分-同花顺代码;证券名称-iFinD数据接口
    datetime_now = datetime.datetime.now()
    s_datetime_now = datetime_now.strftime('%Y-%m-%d')
    b_data = THS_DataPool('block', s_datetime_now + ';001005010', 'thscode:Y', True)
    str1 = str(b_data, 'utf-8')
    data = eval(str1)
    #
    symbol_list = data["tables"][0]["table"]["THSCODE"]
    print(symbol_list)

    #
    step = 1000
    for i in range(0, len(symbol_list), step):
        # if i < 500:
        #     continue
        #
        print("Download_MutualFund_List", i, "to", i + step)
        symbol_list_tmp = symbol_list[i:i + step]

        if "010885.OF" not in symbol_list:
            continue

        #
        # skip_symbols = ["005966.OF", "005965.OF"]
        # for skip_symbol in skip_symbols:
        #     if skip_symbol in symbol_list_tmp:
        #         symbol_list_tmp.remove(skip_symbol)

        Download_Stock_Info(database, symbol_list_tmp)
        a = 0


#
def Download_Stock_Info(database, symbols):
    #
    str_symbols = ",".join(symbols)

    fields_map = {}
    # ---基本要素---
    fields_map["ths_stock_short_name_stock"] = "description"  # 股票简称
    fields_map["ths_listing_exchange_stock"] = "exchange"  # 交易所
    fields_map["ths_stock_code_stock"] = "raw_code" # 股票代码
    fields_map["ths_listedsector_stock"] = "market"  # 上市板块
    #
    fields_map["ths_ipo_date_stock"] = "datetime1" # 上市日期
    fields_map["ths_listed_status_stock"] = "datetime2" # 退市日期
    #
    request_fields = list(fields_map.keys())
    str_request_fields = ";".join(request_fields)
    #
    params = []
    for i in range(len(request_fields)):
        params.append("")
    str_params = ";".join(params)

    #
    b_data = THS_BasicData(str_symbols, str_request_fields, str_params, True)
    try:
        guess_encoding = chardet.detect(b_data)
        str1 = str(b_data, guess_encoding["encoding"])
    except:
        str1 = str(b_data, "gbk")

    try:
        data = json.loads(str1)
    except:
        str1 = str1.strip()
        str1 = str1.replace('\\n', '').replace('\\r', '')
        str1 = str1.replace('\\', '')

        # data = eval(str1)
        # print(str1)
        data = json.loads(str1)


def Download_Stock_Industry_Info(database, symbols):
    #
    datetime_now = datetime.datetime.now()
    s_datetime_now = datetime_now.strftime('%Y-%m-%d')

    # 基础数据-股票-所属申万行业;所属中信行业-iFinD数据接口
    level = 100
    THS_BasicData('000001.SZ', 'ths_the_sw_industry_stock;ths_the_citic_industry_stock',
                  level + ',' + s_datetime_now + ';' + level + ',' + s_datetime_now, True)


if __name__ == '__main__':
    #
    # ---Connect to DataBase, Find Series 连接数据库---
    from Core.Config import *
    pathfilename = os.getcwd() + "\..\Config\config2.json"
    config = Config(pathfilename)
    database = config.DataBase("JDMySQL")
    realtime = config.RealTime()
    #
    a = THS_iFinDLogin('jd1079', '898132')